using System.Diagnostics;
using Microsoft.Win32.TaskScheduler;
using DeleteOnTimeTool.Models;

namespace DeleteOnTimeTool.Services
{
    public static class SchedulerService
    {
        public static void RegisterDailyTask(string hourLocal)
        {
            // 使用 Windows 计划任务，每天固定时间以静默模式运行本程序
            var exePath = Process.GetCurrentProcess().MainModule?.FileName ?? Environment.ProcessPath ?? "";
            if (string.IsNullOrWhiteSpace(exePath)) return;

            const string taskName = "DeleteOnTimeTool.DailyClean";

            using var ts = new TaskService();
            var td = ts.NewTask();
            td.RegistrationInfo.Description = "Delete files by configured rules (DeleteOnTimeTool)";

            var timeSpan = TimeSpan.Parse(hourLocal);
            td.Triggers.Add(new DailyTrigger { DaysInterval = 1, StartBoundary = DateTime.Now.Date.AddSeconds(timeSpan.TotalSeconds) });

            var action = new ExecAction(exePath, "--silent", Path.GetDirectoryName(exePath));
            td.Actions.Add(action);

            // 简化任务设置，避免与登录类型的兼容性问题
            td.Settings.StartWhenAvailable = true;
            td.Principal.RunLevel = TaskRunLevel.Highest;

            // 使用交互式令牌，确保任务在当前用户会话中运行
            ts.RootFolder.RegisterTaskDefinition(taskName, td, TaskCreation.CreateOrUpdate, null, null, TaskLogonType.InteractiveToken);
        }

        public static void UnregisterDailyTask()
        {
            const string taskName = "DeleteOnTimeTool.DailyClean";

            using var ts = new TaskService();
            try
            {
                var task = ts.GetTask(taskName);
                if (task != null)
                {
                    ts.RootFolder.DeleteTask(taskName, false);
                }
            }
            catch (Exception ex)
            {
                // 如果任务不存在，忽略异常
                if (!ex.Message.Contains("找不到指定的任务"))
                {
                    throw;
                }
            }
        }

        public static bool IsTaskRegistered()
        {
            const string taskName = "DeleteOnTimeTool.DailyClean";

            using var ts = new TaskService();
            try
            {
                var task = ts.GetTask(taskName);
                return task != null;
            }
            catch
            {
                return false;
            }
        }
    }
}


